"use client"

import { useState, useRef, useEffect } from "react"
import { View, Text, StyleSheet, TouchableOpacity, Platform, Animated, Alert } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { LinearGradient } from "expo-linear-gradient"
import { ArrowLeft, List, Volume2, Mic, Play, Square, SkipBack, SkipForward, Star } from "lucide-react-native"
import { useRouter } from "expo-router"
import { theme } from "../../constants/theme"
import { ProgressBar } from "../../components/practices/ProgressBar"
import { WordListModal, type WordListItem } from "../../components/practices/WordListModal"

// 模拟的练习数据
const PRACTICE_DATA = [
    {
        id: "1",
        word: "cry",
        phonetic: "/kraɪ/",
        meaning: "v. 哭；呼喊\nn. 哭；呼喊",
        audioUrl: "https://example.com/audio/cry.mp3",
        phonemes: [
            { letter: "c", sound: "/k/" },
            { letter: "r", sound: "/r/" },
            { letter: "y", sound: "/aɪ/" },
        ],
    },
    {
        id: "2",
        word: "smile",
        phonetic: "/smaɪl/",
        meaning: "v. 微笑\nn. 微笑",
        audioUrl: "https://example.com/audio/smile.mp3",
        phonemes: [
            { letter: "s", sound: "/s/" },
            { letter: "m", sound: "/m/" },
            { letter: "i", sound: "/aɪ/" },
            { letter: "le", sound: "/l/" },
        ],
    },
]

export default function ReadingScreen() {
    const router = useRouter()
    const [currentIndex, setCurrentIndex] = useState(0)
    const [isRecording, setIsRecording] = useState(false)
    const [hasRecording, setHasRecording] = useState(false)
    const [isPlaying, setIsPlaying] = useState(false)
    const [score, setScore] = useState<number | null>(null)
    const [listModalVisible, setListModalVisible] = useState(false)
    const [recordingDuration, setRecordingDuration] = useState(0)
    const recordingTimer = useRef<NodeJS.Timeout | null>(null)

    // 动画值
    const recordingPulse = useRef(new Animated.Value(1)).current
    const scoreScale = useRef(new Animated.Value(0)).current

    // 当前单词
    const currentWord = PRACTICE_DATA[currentIndex]

    // 录音动画
    useEffect(() => {
        let animation: Animated.CompositeAnimation
        if (isRecording) {
            animation = Animated.loop(
                Animated.sequence([
                    Animated.timing(recordingPulse, {
                        toValue: 1.2,
                        duration: 1000,
                        useNativeDriver: true,
                    }),
                    Animated.timing(recordingPulse, {
                        toValue: 1,
                        duration: 1000,
                        useNativeDriver: true,
                    }),
                ]),
            )
            animation.start()
        } else {
            recordingPulse.setValue(1)
        }

        return () => {
            if (animation) {
                animation.stop()
            }
        }
    }, [isRecording, recordingPulse])

    // 处理录音计时
    useEffect(() => {
        if (isRecording) {
            recordingTimer.current = setInterval(() => {
                setRecordingDuration((prev) => prev + 1)
            }, 1000)
        } else {
            if (recordingTimer.current) {
                clearInterval(recordingTimer.current)
            }
            setRecordingDuration(0)
        }

        return () => {
            if (recordingTimer.current) {
                clearInterval(recordingTimer.current)
            }
        }
    }, [isRecording])

    // 开始录音
    const startRecording = () => {
        setIsRecording(true)
        // TODO: 实现实际的录音逻辑
    }

    // 停止录音
    const stopRecording = () => {
        setIsRecording(false)
        setHasRecording(true)
        // 模拟评分
        const randomScore = Math.floor(Math.random() * 5) + 1
        setScore(randomScore)

        // 评分动画
        Animated.spring(scoreScale, {
            toValue: 1,
            friction: 8,
            tension: 40,
            useNativeDriver: true,
        }).start()
    }

    // 播放录音
    const playRecording = () => {
        if (!hasRecording) return
        setIsPlaying(true)
        // 模拟播放
        setTimeout(() => {
            setIsPlaying(false)
        }, 2000)
    }

    // 播放标准发音
    const playStandardAudio = () => {
        if (isPlaying) return
        setIsPlaying(true)
        // 模拟播放
        setTimeout(() => {
            setIsPlaying(false)
        }, 1500)
    }

    // 上一个
    const handlePrevious = () => {
        if (currentIndex > 0) {
            setCurrentIndex(currentIndex - 1)
            resetState()
        }
    }

    // 下一个
    const handleNext = () => {
        if (currentIndex < PRACTICE_DATA.length - 1) {
            setCurrentIndex(currentIndex + 1)
            resetState()
        }
    }

    // 重置状态
    const resetState = () => {
        setHasRecording(false)
        setScore(null)
        scoreScale.setValue(0)
    }

    // 返回上一页
    const handleBack = () => {
        if (isRecording) {
            Alert.alert(
                "确认返回",
                "正在录音中，确定要返回吗？",
                [
                    { text: "取消", style: "cancel" },
                    { text: "确定", onPress: () => router.back() },
                ],
                { cancelable: true },
            )
        } else {
            router.back()
        }
    }

    // 跳转到指定单词
    const jumpToWord = (index: number) => {
        setCurrentIndex(index)
        setListModalVisible(false)
        resetState()
    }

    // 准备单词列表数据
    const wordListData: WordListItem[] = PRACTICE_DATA.map((item) => ({
        id: item.id,
        word: item.word,
        phonetic: item.phonetic,
        meaning: item.meaning,
    }))

    // 渲染星级评分
    const renderStars = () => {
        return Array(5)
            .fill(0)
            .map((_, index) => (
                <Star
                    key={index}
                    size={24}
                    color={score && index < score ? theme.colors.secondary.orange.default : theme.colors.neutral.lightGray}
                    fill={score && index < score ? theme.colors.secondary.orange.default : "none"}
                />
            ))
    }

    // 添加音素点击处理函数
    const handlePhonemePress = (phoneme: string, sound: string) => {
        Alert.alert(`音素: ${phoneme}`, `发音: ${sound}`, [{ text: "确定", style: "default" }])
    }

    return (
        <SafeAreaView style={styles.container} edges={["top"]}>
            <LinearGradient
                colors={theme.colors.neutral.backgroundGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
                style={styles.gradientBackground}
            >
                {/* 头部 */}
                <View style={styles.header}>
                    <TouchableOpacity onPress={handleBack} style={styles.headerButton}>
                        <ArrowLeft size={24} color={theme.colors.neutral.black} />
                    </TouchableOpacity>
                    <Text style={styles.headerTitle}>朗读评测</Text>
                    <TouchableOpacity onPress={() => setListModalVisible(true)} style={styles.headerButton}>
                        <List size={24} color={theme.colors.neutral.black} />
                    </TouchableOpacity>
                </View>

                {/* 进度条 */}
                <ProgressBar current={currentIndex + 1} total={PRACTICE_DATA.length} showText={true} textPosition="top" />

                {/* 主要内容 */}
                <View style={styles.content}>
                    <View style={styles.wordCard}>
                        {/* 单词 */}
                        <Text style={styles.word}>{currentWord.word}</Text>

                        {/* 音标和发音按钮 */}
                        <View style={styles.phoneticContainer}>
                            <Text style={styles.phonetic}>{currentWord.phonetic}</Text>
                            <TouchableOpacity
                                style={styles.soundButton}
                                onPress={playStandardAudio}
                                disabled={isPlaying}
                                activeOpacity={0.7}
                            >
                                <Volume2 size={20} color={theme.colors.primary.default} />
                            </TouchableOpacity>
                        </View>

                        {/* 中文释义 */}
                        <Text style={styles.meaning}>{currentWord.meaning}</Text>

                        {/* 录音播放按钮 - 仅在有录音时显示 */}
                        {hasRecording && (
                            <TouchableOpacity
                                style={styles.recordingPlayButton}
                                onPress={playRecording}
                                disabled={isPlaying}
                                activeOpacity={0.7}
                            >
                                <LinearGradient
                                    colors={["rgba(91, 142, 244, 0.1)", "rgba(91, 142, 244, 0.2)"]}
                                    style={styles.recordingPlayButtonGradient}
                                >
                                    <Play size={20} color={theme.colors.primary.default} />
                                    <Text style={styles.recordingPlayText}>{isPlaying ? "播放中..." : "播放我的录音"}</Text>
                                </LinearGradient>
                            </TouchableOpacity>
                        )}

                        {/* 音素分解 */}
                        {score !== null && (
                            <Animated.View
                                style={[
                                    styles.phonemesContainer,
                                    {
                                        transform: [{ scale: scoreScale }],
                                    },
                                ]}
                            >
                                {currentWord.phonemes.map((phoneme, index) => (
                                    <TouchableOpacity
                                        key={index}
                                        style={styles.phonemeItem}
                                        onPress={() => handlePhonemePress(phoneme.letter, phoneme.sound)}
                                        activeOpacity={0.7}
                                    >
                                        <Text style={styles.phonemeLetter}>{phoneme.letter}</Text>
                                        <Text style={styles.phonemeSound}>{phoneme.sound}</Text>
                                        <Text style={styles.phonemeScore}>0</Text>
                                    </TouchableOpacity>
                                ))}
                            </Animated.View>
                        )}

                        {/* 评分 */}
                        {score !== null && (
                            <Animated.View
                                style={[
                                    styles.scoreContainer,
                                    {
                                        transform: [{ scale: scoreScale }],
                                    },
                                ]}
                            >
                                <Text style={styles.scoreLabel}>评分: {score}</Text>
                                <View style={styles.starsContainer}>{renderStars()}</View>
                            </Animated.View>
                        )}
                    </View>

                    {/* 录音控制 */}
                    <View style={styles.controls}>
                        <TouchableOpacity style={styles.controlButton} onPress={handlePrevious}>
                            <SkipBack size={24} color={theme.colors.primary.default} />
                        </TouchableOpacity>

                        <TouchableOpacity
                            style={styles.recordButton}
                            onLongPress={startRecording}
                            onPressOut={isRecording ? stopRecording : undefined}
                            delayLongPress={500}
                            activeOpacity={0.7}
                        >
                            <LinearGradient colors={theme.colors.primary.gradient} style={styles.recordButtonGradient}>
                                <Animated.View
                                    style={[
                                        styles.recordButtonInner,
                                        {
                                            transform: [{ scale: recordingPulse }],
                                        },
                                    ]}
                                >
                                    {isRecording ? (
                                        <Square size={32} color={theme.colors.neutral.white} />
                                    ) : (
                                        <Mic size={32} color={theme.colors.neutral.white} />
                                    )}
                                </Animated.View>
                            </LinearGradient>
                        </TouchableOpacity>

                        <TouchableOpacity style={styles.controlButton} onPress={handleNext}>
                            <SkipForward size={24} color={theme.colors.primary.default} />
                        </TouchableOpacity>
                    </View>

                    {/* 录音提示 */}
                    <Text style={styles.recordingHint}>
                        {isRecording ? `录音中 ${recordingDuration}s` : hasRecording ? "长按重新录音" : "长按开始录音"}
                    </Text>
                </View>

                {/* 单词列表弹窗 */}
                <WordListModal
                    visible={listModalVisible}
                    data={wordListData}
                    currentIndex={currentIndex}
                    onClose={() => setListModalVisible(false)}
                    onSelectWord={jumpToWord}
                    title="单词列表"
                />
            </LinearGradient>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.background,
    },
    gradientBackground: {
        flex: 1,
    },
    header: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
    },
    headerButton: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(255, 255, 255, 0.5)",
    },
    headerTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
    },
    content: {
        flex: 1,
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingBottom: Platform.OS === "ios" ? 34 : theme.spacing.lg,
    },
    wordCard: {
        flex: 1,
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.extraLarge,
        padding: theme.spacing.xl,
        marginBottom: theme.spacing.lg,
        alignItems: "center",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    word: {
        fontSize: 36,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.primary.default,
        marginBottom: theme.spacing.md,
    },
    phoneticContainer: {
        flexDirection: "row",
        alignItems: "center",
        marginBottom: theme.spacing.lg,
    },
    phonetic: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
        marginRight: theme.spacing.sm,
    },
    soundButton: {
        width: 36,
        height: 36,
        borderRadius: 18,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        alignItems: "center",
        justifyContent: "center",
    },
    meaning: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        textAlign: "center",
        marginBottom: theme.spacing.xl,
    },
    phonemesContainer: {
        flexDirection: "row",
        justifyContent: "center",
        flexWrap: "wrap",
        gap: theme.spacing.sm,
        marginBottom: theme.spacing.lg,
    },
    phonemeItem: {
        alignItems: "center",
        backgroundColor: theme.colors.neutral.lightGray,
        borderRadius: theme.borderRadius.medium,
        padding: theme.spacing.sm,
        minWidth: 45,
        height: 70,
    },
    phonemeLetter: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.primary.default,
        marginBottom: 2,
    },
    phonemeSound: {
        fontSize: theme.fontSize.xs,
        color: theme.colors.neutral.darkGray,
        marginBottom: 2,
    },
    phonemeScore: {
        fontSize: theme.fontSize.sm,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.secondary.orange.default,
    },
    scoreContainer: {
        alignItems: "center",
    },
    scoreLabel: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.sm,
    },
    starsContainer: {
        flexDirection: "row",
        gap: theme.spacing.xs,
    },
    controls: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        gap: theme.spacing.xl,
        marginTop: theme.spacing.xxxl,
    },
    controlButton: {
        width: 48,
        height: 48,
        borderRadius: 24,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(91, 142, 244, 0.1)",
    },
    recordButton: {
        width: 64,
        height: 64,
        borderRadius: 32,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 6,
            },
        }),
    },
    recordButtonGradient: {
        width: "100%",
        height: "100%",
        alignItems: "center",
        justifyContent: "center",
    },
    recordButtonInner: {
        width: "100%",
        height: "100%",
        alignItems: "center",
        justifyContent: "center",
    },
    playButton: {
        width: 64,
        height: 64,
        borderRadius: 32,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 6,
            },
        }),
    },
    playButtonGradient: {
        width: "100%",
        height: "100%",
        alignItems: "center",
        justifyContent: "center",
    },
    recordingHint: {
        textAlign: "center",
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
        marginTop: theme.spacing.md,
    },
    recordingPlayButton: {
        marginBottom: theme.spacing.lg,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        alignSelf: "center",
    },
    recordingPlayButtonGradient: {
        flexDirection: "row",
        alignItems: "center",
        paddingVertical: theme.spacing.sm,
        paddingHorizontal: theme.spacing.lg,
        borderRadius: theme.borderRadius.large,
    },
    recordingPlayText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.medium,
        marginLeft: theme.spacing.xs,
    },
})

